package com.xiaowen.tool;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.MessageUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Spring Context 工具类
 */
@Slf4j
@Component
public class SpringContextUtils implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        Object object = null;
        try {
            object = applicationContext.getBean(name);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return object;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    public static <T> List<T> getBeansByType(Class<T> clazz) {
        Map<String, T> beanMaps = applicationContext.getBeansOfType(clazz);
        if (CollectionUtil.isEmpty(beanMaps)) {
            return Collections.emptyList();
        }

        return new ArrayList<>(beanMaps.values());
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }

    public static String getRequestToken(){
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return getRequestToken(request);
    }
    //设备连接时无法获取语言  采用最后一次获取值
    public static String connect_language = "en";
    /**
     * 获取请求的token
     */
    private static String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }
        return token;
    }

}
